'use strict';

const { Controller } = require('egg');
const fs = require('fs')
const path = require('path')

class SucaiController extends Controller {
  async shenhe() {
    const { ctx } = this;
    let start = this.ctx.request.query.start
    const results = await this.app.mysql.query(`select * from b_img limit ${start},4`)
    console.log(results)
    ctx.body = {
      code: 1,
      data: results
    };
  }
  async deleteimg() {
    const { ctx } = this;
    let pid = this.ctx.request.query.pid
    const results = await this.app.mysql.query(`DELETE FROM b_img WHERE pid = ${pid}`)
    console.log(results)
    ctx.body = {
      code: 1,
      data: '删除成功'
    };
  }
  async design() {
    const { ctx } = this;
    let files = ctx.request.files
    let seriesname = ctx.request.body.text
    console.log(files, seriesname)
    let imgname = []

    // 循环将每一张图片复制到img文件夹中
    files.forEach(item => {
      // 复制过去后的名字是传过来的文件名
      fs.copyFileSync(item.filepath, `${path.dirname(__dirname)}/public/img/${item.filename}`);
      imgname.push(item.filename)
    })

    // 先将设计趋势系列名字插入数据
    const re_id = await this.app.mysql.query(`select did from design where dtitle=?`, [`${seriesname}`])
    if (re_id.length != 0) {
      // 说明查到内容，表示已经存在这个系列
      let did = re_id[0].did
      console.log('系列id', did)
      // 循环将每一张图片插入表，要有一个系列id
      imgname.forEach(async el => {
        // console.log(el,'=====')
        const results = await this.app.mysql.query(`insert into design_img(ximg,did) values('/img/${el}',${did})`)
      })
      ctx.body = {
        code: 1,
        data: '添加成功'
      };
    } else {
      // 没查到，则插入这个系列
      const results = await this.app.mysql.query(`insert into design(dtitle) values(?)`, [`${seriesname}`])

      //   setTimeout(()=>{
      //    // 查询插入后的did，循环将每一张图片插入表，要有一个系列id
      //    const did = this.app.mysql.query(`select did from design where dtitle=?`,[`${seriesname}`])
      //     imgname.forEach(el=>{
      //        console.log(el,'=====',did)
      //        const results2 = this.app.mysql.query(`insert into design_img(ximg,did) values('/img/${el}',${did})`)
      //     })
      //     ctx.body = {
      //       code: 1,
      //       data: '添加成功'
      //     };
      //  },100)

      setTimeout(() => {
        // 查询插入后的did，循环将每一张图片插入表，要有一个系列id
        this.app.mysql.query(`select did from design where dtitle=?`, [`${seriesname}`])
          .then((result) => {
            const did = result[0].did; // 假设查询结果是一个对象数组
            imgname.forEach((el) => {
              console.log(el, '=====', did);
              this.app.mysql.query(`insert into design_img(ximg, did) values('/img/${el}', ${did})`)
            });
          })
      }, 100);
      ctx.body = {
        code: 1,
        data: '添加成功'
      };
    }
  }
}

module.exports = SucaiController;
